import Vue from 'vue'
import VueRouter from 'vue-router'
import LoginPage from '@/components/LoginPage.vue'
import HomePage from '@/components/HomePage.vue'


Vue.use(VueRouter)
const routes = [
  { path: '/', redirect: '/login' },
  {
    path: '/login',
    name: 'login',
    component: LoginPage
  },
  {
    path: '/home',
    name: 'home',
    component: HomePage,
    children: [
      { path: '/home', redirect: '/user' },
      { path: '/user', component: ()=> import('@/components/UserPage') },
      { path: '/useradd', component: ()=> import('@/components/UserAdd') },
      { path: '/useredit', component: () => import('@/components/UserEdit') },
      { path: '/notice',component:()=>import('@/components/NoticePage')},//公告列表页面
      { path: '/noticeadd',component:()=>import('@/components/NoticeAdd')},//公告添加页面
      { path: '/noticeedit',component:()=>import('@/components/NoticeEdit')},//公告编辑页面
      { path: '/employee',component:()=>import('@/components/EmployeePage')},//员工列表页面
      { path: '/employeeadd',component:()=>import('@/components/EmployeeAdd')},//员工添加页面
      { path: '/employeeedit',component:()=>import('@/components/EmployeeEdit')},//员工编辑页面
      { path: '/document',component:()=>import('@/components/DocumentPage')},//文档列表页面
      { path: '/documentupload',component:()=>import('@/components/DocumentUpload')},//文档上传页面
      { path: '/documentedit',component:()=>import('@/components/DocumentEdit')},//文档编辑页面
      { path: '/job',component:()=>import('@/components/JobPage')},//职位列表页面
      { path: '/jobadd',component:()=>import('@/components/JobAdd')},//职位添加
      { path: '/jobedit',component:()=>import('@/components/JobEdit')},//职位编辑页面
      { path:'/deptlist',component:()=>import('@/components/DeptList')},//部门列表页面
      { path:'/deptadd',component:()=>import('@/components/DeptAdd')},//部门添加页面
      { path: '/deptedit',component:()=>import('@/components/DeptEdit')}//部门编辑页面
    ]
  },


]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 挂载路由导航守卫,to表示将要访问的路径，from表示从哪里来，next是下一个要做的操作
router.beforeEach((to, from, next) => {
  if (to.path === '/login'||to.path === '/users/logout'||to.path === '/logout') return next()
  // 获取token
  const tokenStr = window.sessionStorage.getItem('token')

  if (!tokenStr) return next('/login')
  //token存在判断是否过期
  if(tokenStr){
    const token = tokenStr;

// 分割JWT并提取Payload部分
    const base64Payload = token.split('.')[1];
    const payload = JSON.parse(atob(base64Payload));

// 获取过期时间戳
    const exp = payload.exp;//过期的时间戳
    const currentTime = Math.floor(Date.now() / 1000); // 获取当前UTC时间的时间戳

// 检查令牌是否过期
    if (exp < currentTime) {
      // 清除本地存储或sessionStorage中的数据
      sessionStorage.clear();

      // 重定向到登录页
      alert("登录过期")
      window.location.href = '/login';
    } else {
      // 令牌有效，继续其他操作
    }
  }
  next()
})
export default router

